package org.csu.mall.service.Impl;


import com.alipay.api.AlipayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.entity.*;
import org.csu.mall.persistence.*;
import org.csu.mall.service.IPayService;
import org.csu.mall.utils.BigDecimalUtil;
import org.csu.mall.utils.NumberUtil;
import org.csu.mall.utils.UsernameUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PayServiceImpl  implements IPayService {
    private static final Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
    @Autowired
    ShippingMapper shippingMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    PayInfoMapper payInfoMapper;
    @Autowired
    OrderItemMapper orderItemMapper;


    private static AlipayTradeService tradeService;
    static {
        /** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
         *  Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
         并会打印一些信息如:pid,appid等
         */
        Configs.init("zfbinfo.properties");
        /** 使用Configs提供的默认参数
         *  AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
         */
        tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
    }

    @Override
    public UniformResponse FastPay(Integer shippingId, Integer paymentType,Integer productId, Integer quantity) {
        String username = UsernameUtil.getUsername("username");
        Integer userId = Integer.parseInt(UsernameUtil.getUserId("userid"));
        if (username == null) {
            return UniformResponse.notLogining();
        } else {
            Shipping shipping = shippingMapper.selectById(shippingId);
            if (shipping == null) {
                return UniformResponse.createForErrorMessage("该地址信息不存在或已删除");
            }
            Product product = productMapper.selectById(productId);
            if (product == null) {
                return UniformResponse.createForErrorMessage("该商品已删除或下架");
            }
            if (quantity > product.getStock()) {
                return UniformResponse.createForErrorMessage("商品库存不足");
            }
            User user = userMapper.selectById(userId);
            if (user == null) {
                return UniformResponse.createForErrorMessage("用户登出或被删除");
            }
            BigDecimal payment = new BigDecimal(0);
            int i = 1;
            while (i <= quantity) {
                payment = payment.add(product.getPrice());
                i = i + 1;
            }
            Order order = new Order();
            order.setUserId(userId);
            BigInteger orderNo = new BigInteger(NumberUtil.genOrderNo());
            order.setOrderNo(orderNo);
            order.setShippingId(shippingId);
            order.setPostage(0);
            order.setPaymentType(paymentType);
            order.setPaymentPrice(payment);
            if (payment.compareTo(user.getBalance()) == 1) {
                return UniformResponse.createForErrorMessage("余额不足，支付失败");
            }
            user.setBalance(BigDecimalUtil.sub(user.getBalance().doubleValue(), payment.doubleValue()));
            user.setUpdateTime(LocalDateTime.now());
            int rows = userMapper.updateById(user);
            if (rows != 0) {
                order.setStatus(CONSTANT.OrderStatus.WAITGOODS.getCode());
                order.setCreateTime(LocalDateTime.now());
                order.setUpdateTime(LocalDateTime.now());

                OrderItem orderItem = new OrderItem();
                orderItem.setOrderNo(orderNo);
                orderItem.setUserId(userId);
                orderItem.setCurrentPrice(product.getPrice());
                orderItem.setQuantity(quantity);
                orderItem.setTotalPrice(payment);
                orderItem.setProductId(productId);
                orderItem.setProductName(product.getName());
                orderItem.setProductImage(product.getMainImage());
                orderItem.setCreateTime(LocalDateTime.now());
                orderItem.setUpdateTime(LocalDateTime.now());
                orderItemMapper.insert(orderItem);
                //支付成功，添加支付信息
                PayInfo payInfo = new PayInfo();
                payInfo.setOrderNo(orderNo);
                payInfo.setPayPlatform(CONSTANT.PayPlatform.BALANCEPAY);
                payInfo.setPlatformNumber(new String(orderNo.toString()));
                payInfo.setPlatformStatus(new String("TRADE_SUCCESS"));
                payInfo.setPayDetail(CONSTANT.payDetail.goodPay);
                payInfo.setUserId(userId);
                payInfo.setCreateTime(LocalDateTime.now());
                payInfo.setUpdateTime(LocalDateTime.now());
                payInfoMapper.insert(payInfo);
                order.setPaymentTime(LocalDateTime.now());
                orderMapper.insert(order);
                return UniformResponse.createForSuccessMessage("支付完成");
            }
            return UniformResponse.createForErrorMessage("支付失败");
        }

    }

    @Override
    public UniformResponse payBalance(BigDecimal balance) {
        String username = UsernameUtil.getUsername("username");
        Integer userId = Integer.parseInt(UsernameUtil.getUserId("userid"));
        if (username == null) {
            return UniformResponse.notLogining();
        } else {
//            Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("user_id", userId).eq("order_no", orderNo));
//            if (order == null) {
//                return UniformResponse.createForErrorMessage("用户没有该订单");
//            }
//            //订单编号
//            String outTradeNo = orderNo.toString();
//            //订单标题
//            String subject = new StringBuilder().append("Mall扫码支付，订单号:").append(outTradeNo).toString();
//            //订单总价
//            String totalAmount = order.getPaymentPrice().toString();
//            //卖家支付宝账号ID
//            //如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
//            String sellerId = "";
//            // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
//            String storeId = "test_store_id";
//            // 支付超时，定义为120分钟
//            String timeoutExpress = "120m";
//
//            List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
//
//            QueryWrapper<OrderItem> queryOrderNoUserId = new QueryWrapper<>();
//            queryOrderNoUserId.eq("order_no", orderNo).eq("user_id", userId);
//            List<OrderItem> orderItemList = orderItemMapper.selectList(queryOrderNoUserId);
//            for (OrderItem orderItem : orderItemList) {
//                GoodsDetail goods = GoodsDetail.newInstance(orderItem.getProductId().toString(), orderItem.getProductName(),
//                        BigDecimalUtil.mul(orderItem.getCurrentPrice().doubleValue(), new Double(100).doubleValue()).longValue(),
//                        orderItem.getQuantity());
//                goodsDetailList.add(goods);
//            }
            String outTradeNo=NumberUtil.genOrderNo();
            UsernameUtil.setOrderNo("orderno",new BigInteger(outTradeNo));
            String subject = new StringBuilder().append("余额充值，订单号:").append(outTradeNo).toString();
            String totalAmount = balance.toString();
            UsernameUtil.setBalance("balance",balance);
            String sellerId = "";
            String storeId = "test_store_id";
            String timeoutExpress = "10m";
            List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
            GoodsDetail goods = GoodsDetail.newInstance(CONSTANT.Balance.id, CONSTANT.Balance.name,
                        BigDecimalUtil.mul(balance.doubleValue(), new Double(100).doubleValue()).longValue(),
                        1);
            // 创建扫码支付请求builder，设置请求参数
            AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                    .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo).setSellerId(sellerId)
                    .setStoreId(storeId).setTimeoutExpress(timeoutExpress)
                    .setNotifyUrl("http://106.55.173.219:18034/fastPay/alipay_callback")//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                    .setGoodsDetailList(goodsDetailList);
            AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
            switch (result.getTradeStatus()) {
                case SUCCESS:
                    logger.info("支付宝预下单成功: )");

                    AlipayTradePrecreateResponse response = result.getResponse();
                    dumpResponse(response);

                    // 需要修改为运行机器上的路径
//                    String filePath = String.format("D:/programs/Git/mall/images/%s.jpg",
//                            response.getOutTradeNo());
                    String filePath=String.format("/notebooks/mall-front/dist/img/pay.jpg");
//                    String qrFileName = String.format( "%s.png", response.getOutTradeNo() );
                    logger.info("filePath:" + filePath);
                    //将二维码图片以长宽为width大小存储在filePath路径下
                    ZxingUtils.getQRCodeImge(response.getQrCode(), 256, filePath);
                    return UniformResponse.createForSuccess("支付宝预下单成功,订单号为",outTradeNo);

                case FAILED:
                    logger.error("支付宝预下单失败!!!");
                    return UniformResponse.createForErrorMessage("支付宝预下单失败!!!");

                case UNKNOWN:
                    logger.error("系统异常，预下单状态未知!!!");
                    return UniformResponse.createForErrorMessage("系统异常，预下单状态未知!!!");

                default:
                    logger.error("不支持的交易状态，交易返回异常!!!");

            }
            return UniformResponse.createForErrorMessage("不支持的交易状态，交易返回异常!!!");
        }
    }

    // 简单打印应答
    private void dumpResponse(AlipayResponse response) {
        if (response != null) {
            logger.info(String.format("code:%s, msg:%s", response.getCode(), response.getMsg()));
            if (StringUtils.isNotEmpty(response.getSubCode())) {
                logger.info(String.format("subCode:%s, subMsg:%s", response.getSubCode(),
                        response.getSubMsg()));
            }
            logger.info("body:" + response.getBody());
        }
    }

    //
    /**
     * 支付宝回调
     * @param params
     * @return 支付状态
     */
    public UniformResponse aliCallback(Map<String ,String > params) {
        BigInteger orderNumber = new BigInteger(String.valueOf(params.get("out_trade_no")));
        String tradeNo = params.get("trade_no");
        String tradeStatus = params.get("trade_status");
//        Order order = orderMapper.selectOne(Wrappers.<Order>query().eq("order_no",orderNumber));
//        if(order == null){
//            return UniformResponse.createForErrorMessage("非本商城的订单，回调忽略");
//        }
//        if(order.getStatus() >= CONSTANT.OrderStatus.PAYED.getCode()){
//            return UniformResponse.createForSuccess("支付宝重复调用");
//        }
//        if(tradeStatus.equals("TRADE_SUCCESS")){
//            order.setPaymentTime(LocalDateTime.now());
//            order.setUpdateTime(LocalDateTime.now());
//            order.setStatus(CONSTANT.OrderStatus.PAYED.getCode());
//            orderMapper.updateById(order);
        logger.info("创建支付信息");
        PayInfo payInfo = new PayInfo();
        Integer userId = Integer.parseInt(UsernameUtil.getUsername("userid"));
        payInfo.setUserId(userId);
        payInfo.setOrderNo(orderNumber);
//            payInfo.setUserId(order.getUserId());
//            payInfo.setOrderNo(order.getOrderNo());
        payInfo.setPayPlatform(CONSTANT.PayPlatform.ALIPAY);
        payInfo.setPlatformNumber(tradeNo);
        payInfo.setPlatformStatus(tradeStatus);
        payInfo.setPayDetail(CONSTANT.payDetail.balancePay);
        payInfo.setCreateTime(LocalDateTime.now());
        payInfo.setUpdateTime(LocalDateTime.now());
        PayInfo payInfo1 = payInfoMapper.selectOne(Wrappers.<PayInfo>query().eq("order_no", orderNumber));
        if (payInfo1 == null) {
            payInfoMapper.insert(payInfo);

            return UniformResponse.createForSuccessMessage(tradeStatus);
        }
        payInfo1.setPlatformStatus(tradeStatus);
        payInfo1.setUpdateTime(LocalDateTime.now());
        payInfoMapper.updateById(payInfo1);
        return UniformResponse.createForSuccessMessage(tradeStatus);
//        }


    }

}
